using System;
using System.Collections.Generic;
using System.Reflection;
using Rhizome.Contract;
using Rhizome.Internal;
using Rhizome.Model.Validation;

namespace Rhizome.Model
{
    public abstract class PropertyActiveItemBase : ActiveItemBase
    {
        private PropertyInfo _propertyInfo;

        protected PropertyInfo PropertyInfo
        {
            get { return _propertyInfo ?? (_propertyInfo = GetPropertyInfo()); }
        }

        public string Property { get; set; }

        private PropertyInfo GetPropertyInfo()
        {
            var plant = Plant;
			//if (plant == null)
			//    throw new ValidationException("Plant can not be null");

            var type = plant.GetType();
            var result = type.GetProperty(Property);
			//if (result == null)
			//    throw new ValidationException(string.Format("Property [{0}.{1}] not found", type, Property));

            return result;
        }

    	#region Implementation of IValidate

    	public override IEnumerable<IValidationResult> GetValidationResults()
    	{
    		foreach (var e in BaseValidate()) yield return e;

    		if (Plant == null) yield return ValidationResult.PlantIsNull;
			if (Property.IsNullOrEmpty()) yield return ValidationResult.PropertyNotSet;
			else if (Plant != null && PropertyInfo == null) yield return ValidationResult.PropertyNotFound(Property, Plant); 
    	}

    	private IEnumerable<IValidationResult> BaseValidate()
    	{
    		return base.GetValidationResults();
    	}

    	#endregion
    }
}